<template>
  <van-nav-bar left-text="返回" left-arrow @click-left="router.go(-1)"/>

  <van-address-edit
      :area-list="areaList"
      :address-info="initAddressInfo"
      show-delete
      show-set-default
      show-search-result
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="handleSave"
      @delete="handleDelete"
  />

</template>


<script setup lang="ts">

import {ref, reactive} from 'vue';
import {useRoute,useRouter} from "vue-router";
import { areaList } from '@vant/area-data';
import { saveAddress,findById,deleteAddressById } from '@/api/address';
const router = useRouter();
const route = useRoute();

const initAddressInfo = reactive({})

let addressId = route.query.id;
if(addressId){
  //根据id查询详情信息
  findById(addressId).then((resp)=>{
    let oriAddressInfo = resp.data;
    if(oriAddressInfo){
      initAddressInfo.id = oriAddressInfo.id;
      initAddressInfo.name = oriAddressInfo.consignee;
      initAddressInfo.tel = oriAddressInfo.phone;

      initAddressInfo.province = oriAddressInfo.provinceName;
      initAddressInfo.city = oriAddressInfo.cityName;
      initAddressInfo.county = oriAddressInfo.areaName;

      initAddressInfo.addressDetail = oriAddressInfo.detail;
      initAddressInfo.isDefault = oriAddressInfo.isDefault;
    }
  })
}

let handleSave = (addressInfo)=>{
  const param ={};
  param.consignee =addressInfo.name;
  param.phone =addressInfo.tel;

  param.provinceName =addressInfo.province;
  param.cityName =addressInfo.city;
  param.areaName =addressInfo.county;

  param.detail =addressInfo.addressDetail;
  param.isDefault =addressInfo.isDefault;

  saveAddress(addressId,param).then((resp)=>{
    showNotify({ type: 'success', message: resp.msg });
    router.push("/address/list");
  }).catch((error)=>{

  })
}


let handleDelete= (addressInfo)=>{
  if(addressId){

    deleteAddressById(addressId).then((resp)=>{
      if(resp.code == 200){
        showNotify({ type: 'success', message: resp.msg });
        router.push("/address/list");
      }
    });
  }else{
    router.push("/address/list");
  }
}


</script>

<style scoped>
</style>